package cloudContact.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mybeans.factory.RollbackException;

import cloudContact.*;
import cloudContact.DAO.*;
import cloudContact.SecurityManager;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Register() {
		super();
		// TODO Auto-generated constructor stub
		
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		try {

			if ((request.getParameter("userName") == null)
					|| (request.getParameter("password") == null)
					|| request.getParameter("userName").toString().isEmpty()
					|| request.getParameter("password").toString().isEmpty()) {
				out.print("Error: Invalid user information");
				return;
			}

			String userName = request.getParameter("userName").toString();

			// Check that user does not exist both in unactivate and user table.
			UnactivatedUserDAO unActDAO = UnactivatedUserDAO.getInstance();
			UserDAO userDAO = UserDAO.getInstance();

			if ((unActDAO.lookup(userName) != null)
					|| (userDAO.lookup(userName) != null)) {
				out.print("Error: The user name already registered.");
				return;
			}

			UnactivatedUser user = new UnactivatedUser();

			user.setEMail(userName);

			// Hash before save.
			user.setPassword(SecurityManager.getHash(request.getParameter("password").toString()));

			user.setCreatedDate(Calendar.getInstance().getTime());

			// Creating a random UUID (Universally unique identifier).
			UUID uuid = UUID.randomUUID();
			user.setActivationCode(uuid.toString());

			unActDAO.create(user);

			// Send Email for user to activate
			Emailer.sendEmail(
					userName,
					"Action Required to Activate Membership for CloudContact",
					"Dear "
							+ userName
							+ ", <br /><br />"
							+ "Thank you for registering to CloudContact. Before we can activate your account one last step must be taken to complete your registration. <br /><br />"
							+ "Please note - you must complete this last step to become a registered member. You will only need to visit this url once to activate your account. <br /><br />"
							+ "To complete your registration, please visit this url:<br />"
							+ "https://cloudctac.dyndns.org/CloudContact/activate.jsp?id=" + user.getUserId() + "&code="	+ uuid.toString() + " <br /><br />"
							+ "or visit https://cloudctac.dyndns.org/CloudContact/activate.jsp and enter user name and the following activation code:<br />"
							+ uuid.toString() + " <br /><br />"
							+ "Cheers, <br />" + "CloudContact.com");
			out.print("Success:");

		} catch (RollbackException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (MyDAOException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (Exception e) {
			out.print(Common.CriticalErrorRaised(e));
		} finally {
			out.flush();
			out.close();
		}
	}
}
